package com.jerry.wschat.web.controller;

import com.jerry.wschat.model.User;
import com.jerry.wschat.model.vo.ReturnVO;
import com.jerry.wschat.security.utils.PasswordEncodeUtils;
import com.jerry.wschat.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

@Api("用户登录")
@Controller
public class IndexController extends BaseController<User, Integer> {

    @Autowired
    private UserService mUserService;

    @ApiOperation(value = "登录页跳转")
    @GetMapping("/login")
    public ModelAndView getLoginView() {
        ModelMap model = new ModelMap();
        return new ModelAndView("loginPage", model);
    }

    @ApiOperation(value = "聊天页跳转")
    @GetMapping("/chat")
    public ModelAndView getChatView() {
        ModelMap modelMap = new ModelMap();
        return new ModelAndView("chat", modelMap);
    }

    @GetMapping("/home")
    public String home() {
        return "index";
    }

    @ApiOperation(value = "注册提交")
    @PostMapping("/register")
    @ResponseBody
    public ReturnVO register(@RequestParam String username, @RequestParam String pwd1, @RequestParam String pwd2,
                             @RequestParam String nickname, @RequestParam String email, @RequestParam int age) {
        if (StringUtils.isEmpty(username) || StringUtils.isEmpty(pwd1)) {
            return ReturnVO.ERROR("用户名或密码不能为空！");
        }
        User user = mUserService.findUserByUsername(username);
        if (user != null) {
            return ReturnVO.ERROR("用户名已存在!");
        }

        user = new User();
        user.setUsername(username);
        user.setNickname(nickname);
        user.setEmail(email);
        user.setAge(age);
        user.setEnabled(true);
        if (!pwd1.equals(pwd2)) {
            return ReturnVO.ERROR("两次密码输入不一致");
        }
        String pwdEncode = PasswordEncodeUtils.bCryptPasswordEncode(pwd1);
        user.setPassword(pwdEncode);

        mUserService.save(user);

        return ReturnVO.OK(user);
    }



}
